import axios from "axios"
import store from "@/store"
import router from "@/router"

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: false, // send cookies when cross-domain requests
  timeout: 60000, // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    if (store.getters.token) {
      // if (config.method === 'get') {
      //   config.params = {
      //     ...config.params,
      //     token: store.getters.token
      //   }
      // }
      // if (config.method === 'post' && !config.isUpload) {
      //   config.data = {
      //     ...config.data,
      //     token: store.getters.token
      //   }
      // }
      config.headers["token"] = store.getters.token
    }
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data

    // // 为百度逆地理解析特殊处理
    // if (res.code) return res

    // const currentPath = router.history.current.path

    // if the custom code is not 200, it is judged as an error.
    if (res.resultCode !== 200) {
      // 601: 无效的token; 602: token已过期;
      if (
        (res.resultCode === 610106 || res.resultCode === 601) &&
        currentPath !== "/" &&
        currentPath !== "/login"
      ) {
        // 如果调用检查token接口就不弹出提示
        if (response.config.url.indexOf("/cc/account/checkToken") === -1) {
          MessageBox.confirm(
            "你的登录状态已经过期, 可以点击取消留在本页, 或者重新登录",
            "过期确认",
            {
              confirmButtonText: "重新登录",
              // cancelButtonText: '取消',
              type: "warning",
            }
          ).then(() => {
            store.dispatch("user/resetToken").then(() => {
              location.reload()
            })
          })
        }
      }
      return Promise.reject(new Error(res.message || "Error"))
    } else {
      return res
    }
  },
  (error) => {
    // console.log('err' + error)
    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    return Promise.reject(error)
  }
)

export default service
